<template>
    <div>
        <el-button type="primary" @click="fetchRoleJson">fetch</el-button>
        | 默认展开深度：<el-input v-model="inputExpend" style="width: 50px;"></el-input>
        | key：<el-input v-model="fetchKey" style="width: 50px;"></el-input>
        <br><br>
        <json-viewer :value="jsonData" copyable boxed :expand-depth="expend" :expanded="true" :key="expend">
        </json-viewer>
    </div>
</template>

<script setup lang="ts">
import { Axios, AxiosResponse } from "axios";
import { computed, inject, onMounted, onUpdated, ref, Ref } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import { Resp, CODE_SUCCESS } from "../../ts/Resp";
import { ElMessage } from "element-plus";

const http = inject<Axios>('http');

const jsonData: Ref<JSON> = ref(JSON.parse('{}'));

const inputExpend = ref("1");
const fetchKey = ref("1");
const expend = computed(() => parseInt(inputExpend.value, 10))

let INTERVAL_ID: any
// --------- function -----------

interface WatchData {
    changed: boolean
    // 他妈的这里居然不能是jData，👎
    jdata: string
    key: string
}

function watchDataToString(_data: WatchData) {
    // return "{ changed: " + _data.changed + ", jdata: " + _data.jdata + "}"
    return "";
}

function fetchRoleJson() {
    http?.get('/erole/json?key=' + fetchKey.value).then((res: AxiosResponse<Resp>) => {
        if (res.data.code == CODE_SUCCESS) {
            const data = res.data.data as WatchData;
            saveScrollPosition()
            // console.log("扯蛋： " + watchDataToString(data));
            jsonData.value = JSON.parse(data.jdata);
        } else {
            // 弹出提示
            ElMessage.error(res.data.message);
            console.log("error: " + res.data.message + "code: " + res.data.code + "data: " + res.data.data);
        }
    });
}

function saveScrollPosition() {
    console.log("save: "+window.scrollY.toString());
    
    sessionStorage.setItem('scrollPosition', window.scrollY.toString());
}

function continueScoll() {
    const scrollPosition = sessionStorage.getItem('scrollPosition');

    if (scrollPosition) {
        const to = parseInt(scrollPosition, 10)
        window.scrollTo(0, to);
    }
}

// ----- vue inner function ------

onMounted(() => {
    INTERVAL_ID = setInterval(() => fetchRoleJson(), 1000)
    // 防止滑动条还原
    // window.addEventListener('scroll', saveScrollPosition);
})
onBeforeRouteLeave(() => {
    clearInterval(INTERVAL_ID)
})
// onBeforeUpdate(saveScrollPosition)
onUpdated(() => setTimeout(continueScoll, 200))

</script>